#include "PadstackDefParser.h"

#include "PadstackPadDefParser.h"
#include "PadstackHoleDefParser.h"
#include "QStringParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

PadstackDefParser::PadstackDefParser(
    QStringParser *&_nameParser
    , PadstackHoleDefParser *&_padstackHoleDefParser
    , PadstackPadDefParser *&_padstackPadDefParser
):    m_nameParser(_nameParser)
    , m_padstackHoleDefParser(_padstackHoleDefParser)
    , m_padstackPadDefParser(_padstackPadDefParser)
{

}

bool PadstackDefParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new PadstackDef());

    /* Attributes */

    QStringRef data;
    if (reader->attributes().hasAttribute(QStringLiteral("name")))
    {
        data = reader->attributes().value(QStringLiteral("name"));
        if (!m_nameParser->parse(reader, data))
            return false;
        m_result->nameOptional = Optional<QString>(m_nameParser->result());
    }

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("PadstackHoleDef"))
        {
            if (!m_padstackHoleDefParser->parse(reader))
                return false;
            auto result = m_padstackHoleDefParser->result();
            m_result->padstackHoleDefList.append(result);
        }
        else if (name == QStringLiteral("PadstackPadDef"))
        {
            if (!m_padstackPadDefParser->parse(reader))
                return false;
            auto result = m_padstackPadDefParser->result();
            m_result->padstackPadDefList.append(result);
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

PadstackDef *PadstackDefParser::result()
{
    return m_result.take();
}

}